#include "srexcelfile.h"

#include <libxl/libxl.h>


#include <thread>

#include <QDebug>

SRExcelFile::SRExcelFile(QObject *parent) : QObject(parent)
{
    isRead_ = false;
}

void SRExcelFile::onReadExcelData(int _beginLine, int _endLine) {
    std::thread(&SRExcelFile::thread_readExcelData, this, _beginLine,
                _endLine).detach();
}

void SRExcelFile::thread_readExcelData(int _beginLine, int _endLine) {
    using namespace libxl;

    Book* book = xlCreateBook();
    if (!book)
        return ;

    if (!book->load(excelFilePath_.toStdString().c_str()))
        return;

    Sheet* sheet = book->getSheet(0);
    if (!sheet)
        return;

    // 默认最后一行
    if (_endLine == -1) {
        _endLine = sheet->lastRow();
    }

    maxLine_ = _endLine;

    isRead_ = true;

    qDebug("导入Excel文件.");
    for (int row = _beginLine; row < _endLine; ++row) {
        if (isRead_ == false) {
            qDebug() << "program terminated, import last line :" << row;
            break;
        }


        if (row > 0 && (row % 140  == 0)) {
            book->release();
            book = xlCreateBook();
            if (!book)
                return;

            if (!book->load(excelFilePath_.toStdString().c_str()))
                return;

            sheet = book->getSheet(0);
            if (!sheet)
                return;
        }

        const QString& phone = QString::number(sheet->readNum(row,0),10,0);
        const QString& name = sheet->readStr(row,1);

        // 弹出数据
        emit sigExcelData(row, name, phone);

    }

    qDebug("导入Excel文件完毕.");

    isRead_ = false;
}
